package com.gues.controller;

import com.gues.eneity.User;
import com.gues.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Resource
    UserService userService;

    @PostMapping("/login")
    public @ResponseBody Map<String, Object> login(@RequestBody User user) {
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> map = new HashMap<>();
        // 验证登录
        subject.login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
        map.put("code", 200);
        map.put("msg", "登陆成功");
        return  map;
    }

    @GetMapping("/admin/logout")
    public @ResponseBody Map<String, Object> logout() {
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> map = new HashMap<>();
        subject.logout();
        map.put("code", 200);
        return map;
    }

    @PostMapping("/admin/changePwd")
    public @ResponseBody Map<String, Object> changePwd(@RequestBody User user) {
        Map<String, Object> map = new HashMap<>();
        System.out.println("进来了");
        user.setId(1);
        user.setUsername("admin");
        int result = userService.change(user);
        if ( result != 0) {
            map.put("code", 200);
            map.put("msg", "修改密码成功");
        } else {
            map.put("code", 401);
            map.put("msg", "修改密码失败");
        }
        return map;
    }
}
